package com.sduept.nwld.dataserver.controller.dataview;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.core.dao.SuperDAO;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.model.param.BreakerTechnicalParameter;
import com.sduept.nwld.dataserver.util.ExicelParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Named
@ViewScoped
public class BreakerImportDbController extends AbstractController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2893977961158685577L;
	@Autowired
	private CimManager cimManger;
	@Autowired
	private SuperDAO dao;
	@Autowired
	private CommonDocumentProperties pros;
	private String errorString ="导入错误:";
	private List<BreakerTechnicalParameter> breakerTechnicalParameters = new ArrayList<BreakerTechnicalParameter>();
	
	@PostConstruct
	public void init(){
		breakerTechnicalParameters = dao.findAll(BreakerTechnicalParameter.class);
	}
	
	public void handleWaveFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String houzhuiming = file.getFileName().substring(
				file.getFileName().lastIndexOf("."));
		String id = ObjectId.get().toString();
		String dirFileName = id + houzhuiming;
		String path = pros.getDocumentPath() + dirFileName;
		try {
			FileOutputStream fos = new FileOutputStream(path);
			fos.write(file.getContents());
			fos.close();
		} catch (IOException ee) {
			ee.printStackTrace();
			addErrorMessage("文件上传失败");
		}
		try {
			importBreaker(path, houzhuiming);
		} finally {
			File deleteFile = new File(path);
			if (deleteFile != null && deleteFile.isFile())
				deleteFile.delete();
		}

	}
	/**
	 * 解析
	 * 
	 * @param path
	 * @param houzhuiming
	 */
	private void importBreaker(String path, String houzhuiming) {
		ExicelParseUtil exicelParseUtil = new ExicelParseUtil();
		List<List<Object>> lo = null;
		if (".xlsx".equals(houzhuiming)) {
			lo = exicelParseUtil.getFirstRowInfoOfXLSX(path, 1, 0);
		}
		if (".xls".equals(houzhuiming)) {
			lo = exicelParseUtil.getFirstRowInfoOfXLS(path, 1, 0);
		}
		if (lo == null) {
			addErrorMessage("文件解析失败，请检查！");
			return;
		}
		List<Breaker> breakers = cimManger.getBreakerBySubNameAndvoltage500();
		StringBuffer buffer = new StringBuffer();
		int num = 0;
		
		for (List<Object> list : lo) {
			String sub_name = list.get(1).toString();// 变电站
			String pathString = list.get(8).toString();// 全路径
			log.info(num++ +"==="+sub_name+"  :");
			for (int i = 0; i < breakers.size(); i++) {
				Breaker breaker = breakers.get(i);
				String sub = breaker.getSubName();
				if (sub.contains("站")||sub.contains("变")) {
					sub = sub.substring(0, sub.length()-1);
				}
				if (sub_name.contains(sub)) {
					if (pathString.contains(breaker.getName())) {
						try {
							String category_name = list.get(4).toString();// 类别名称
							Date commissioning_date = new SimpleDateFormat(
									"yyyy-MM-dd hh:mm:ss").parse(list.get(6)
									.toString());// 投运日期
							String manufacturer = list.get(9).toString();// 厂家
							String type = list.get(10).toString();// 型号
							BreakerTechnicalParameter breakerTechnicalParameter = new BreakerTechnicalParameter();
							breakerTechnicalParameter.setId(breaker.getId());
							breakerTechnicalParameter
									.setName(breaker.getName());
							breakerTechnicalParameter.setBreaker_name(breaker
									.getName());
							breakerTechnicalParameter
									.setCategory_name(category_name);
							breakerTechnicalParameter
									.setCommissioning_date(commissioning_date);
							breakerTechnicalParameter
									.setManufacturer(manufacturer);
							breakerTechnicalParameter.setType(type);
							breakerTechnicalParameter.setVoltage(breaker
									.getStandVoltagelevel() + "");
							// 插入/更新数据库
							dao.createOrUpdate(breakerTechnicalParameter,
									BreakerTechnicalParameter.class);
							break;
						} catch (ParseException e) {
							e.printStackTrace();
						}
					} else if (i == breakers.size() - 1) {
						if( list.get(7).toString().contains("500")){
						buffer.append("\n断路器不存在：" + list.get(2).toString());
						}
					}
				} else if (i == breakers.size() - 1) {
					// 数据库中没有该数据
					if( list.get(7).toString().contains("500")){
						buffer.append("\n变电站不存在： " + sub_name);
					}
				}
			}
		}
		errorString =errorString+buffer.toString();
		addSuccessMessage("文件解析成功");
	}

	public String getErrorString() {
		return errorString;
	}

	public void setErrorString(String errorString) {
		this.errorString = errorString;
	}

	public List<BreakerTechnicalParameter> getBreakerTechnicalParameters() {
		return breakerTechnicalParameters;
	}

	public void setBreakerTechnicalParameters(
			List<BreakerTechnicalParameter> breakerTechnicalParameters) {
		this.breakerTechnicalParameters = breakerTechnicalParameters;
	}
}
